//
//  CancelYuYueViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-20.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "CancelYuYueViewController.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"
#import "YuYueListViewController.h"

#define kReasonDownloaderKey    @"ReasonDownloaderKey"
#define kCancelDownloaderKey    @"CancelDownloaderKey"

@interface CancelYuYueViewController ()

@end

@implementation CancelYuYueViewController

@synthesize productDetail;
@synthesize nameLabel,reasonLabel,reasonPickView;
@synthesize reasonArray;

- (NSString *)checkValid
{
    if(reasonLabel.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"取消原因"];
    return nil;
}

- (IBAction)confirmButtonClicked:(id)sender
{
    NSString *validString = [self checkValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSInteger index = [self.reasonPickView selectedRowInComponent:0];
        NSDictionary *dict = [self.reasonArray objectAtIndex:index];
        NSString *code = [dict objectForKey:@"csCode"];
        
        NSString *suburl = [NSString stringWithFormat:kCancelYuyueUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,self.productDetail.sf_opportunity_id,code,@""];
        suburl = [suburl stringByAppendingString:@"app000043"];
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kCancelDownloaderKey];
    }
}


#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightItemTapped
{
    NSArray *properties = [NSArray arrayWithObject:@"Call"];
    NSMutableDictionary *filterInfo = [NSMutableDictionary dictionary];
    [filterInfo setObject:properties forKey:kFilterPropertiesKey];
    [filterInfo setObject:[NSNumber numberWithInt:kLocationRight] forKey:kFilterLocationType];
    [filterInfo setObject:[NSNumber numberWithInteger:kProYuyueCancel] forKey:kFilterTypeKey];
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowFilterViewNotification object:nil userInfo:filterInfo];
}


#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"取消预约"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:@"Icon_Dial"];
    
    self.nameLabel.text = self.productDetail.public_product_name;
    
    NSString *suburl = [NSString stringWithFormat:kFindDictBykindTypeUrl,@"jsonp",@"0010"];
    suburl = [suburl stringByAppendingString:@"app000042"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kReasonDownloaderKey];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.nameLabel = nil;
        self.reasonLabel = nil;
        self.reasonPickView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.nameLabel = nil;
    self.reasonLabel = nil;
    self.reasonPickView = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [reasonArray release];
    [reasonPickView release];
    [nameLabel release];
    [reasonLabel release];
    [productDetail release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kCancelDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshYuyueProductsNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshOnlneProductsNotification object:nil];
            UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"您已成功取消预约" message:nil delegate:self cancelButtonTitle:@"我的预约" otherButtonTitles:@"继续浏览", nil] autorelease];
            [av show];
        }
        else
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
    else
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            NSArray *array = [dict objectForKey:@"resultlist"];
            self.reasonArray = array;
            [self.reasonPickView reloadAllComponents];
            if(array.count > 0)
            {
                [self.reasonPickView selectRow:0 inComponent:0 animated:NO];
                [self pickerView:self.reasonPickView didSelectRow:0 inComponent:0];
            }
        }
        else
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
    }

}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UIAlertViewDelegate methods
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        YuYueListViewController *yylvc = [[YuYueListViewController alloc] init];
        yylvc.isFromEdit = YES;
        [self.navigationController pushViewController:yylvc animated:YES];
        [yylvc release];
    }
    else if(buttonIndex == 1)
    {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }
}

#pragma mark - UIPickerViewDataSource methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.reasonArray.count;
}

#pragma mark - UIPickerViewDelegate methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [[self.reasonArray objectAtIndex:row] objectForKey:@"sfCode"];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.reasonLabel.text = [[self.reasonArray objectAtIndex:row] objectForKey:@"sfCode"];
}

@end
